package team27.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import team27.messaging.Message;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class TestClient {

	public static void main(String[] args) throws IOException {

		ClientConfig config = new DefaultClientConfig();
		Client client = Client.create(config);
		WebResource service = client.resource(getBaseURI());
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		int opt = 0;
		String myId = null;

		System.out.println("******Welcome to MessageBook******");
		

		myId = service.path("login").accept(MediaType.APPLICATION_JSON)
				.get(String.class);
		

		while (opt != 3) {

			menu();

			try {
				opt = Integer.parseInt(br.readLine());
			} catch (NumberFormatException nfe) {
				System.err.println("Invalid Format!");
			}

			switch (opt) {
			case 1:
				System.out.println("Write down your message : ");

				String s = null;
				try {
					s = br.readLine();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				Message msg = new Message(myId, s);
				ClientResponse response = service.accept(
						MediaType.APPLICATION_JSON).put(ClientResponse.class,
						msg);

				System.out.println(response);
				break;

			case 2:
				// Get JSON for application
				System.out.println(service.accept(MediaType.APPLICATION_JSON)
						.get(String.class));

				break;

			case 3:
				System.out.println("Thanks for using messageBook");
				System.out.println("Amount to be paid is " + service.path("logout").accept(MediaType.APPLICATION_JSON)
						.get(String.class));
				break;

			default:
				break;
			}

		}

	}

	private static void menu() {

		System.out.println("-------------------------");
		System.out.println("1 : Send a message");
		System.out.println("2 : Read all the chatroom");
		System.out.println("3 : Exit the service and pay");
		System.out.println("-------------------------");
		System.out.println("Write your option here :");

	}

	private static URI getBaseURI() {
		return UriBuilder.fromUri("http://localhost:8080/Team_27").build();
	}
}
